// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package roadmap_rag_api_serv

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"math"
	"net/http"
	"strings"

	"gitcode.com/lvupclub/lvup-api/dao/roadmap_dao"
	"gitcode.com/lvupclub/proto-gen-go.git/src/roadmap_rag_api"
)

type FastGptMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type FastGptRequest struct {
	AppId    string           `json:"appId"`
	Stream   bool             `json:"stream"`
	Messages []FastGptMessage `json:"messages"`
}

type FastGptChoiceDetail struct {
	Content string `json:"content"`
}

type FastGptChoice struct {
	Delta FastGptChoiceDetail `json:"delta"`
}

type FastGptAnswerItem struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	ID      string          `json:"id"`
	Choices []FastGptChoice `json:"choices"`
}

func (apiImpl *RoadmapRagApiImpl) processFastGpt(s roadmap_rag_api.RoadmapRagApi_SendMessageServer, ragConfigItem *roadmap_dao.RagConfigDbItem, ownerUserId, assistantMessageId string, assistantTimeStamp int64) (string, error) {
	ctx := s.Context()
	//列出最近5条内容
	msgItemList, err := roadmap_dao.ChatMessageDao.List(ctx, ragConfigItem.RoadmapId, ragConfigItem.RagConfigId, ownerUserId, math.MaxInt64, roadmap_rag_api.LIST_MESSAGE_TYPE_LIST_MESSAGE_BEFORE, 5)
	if err != nil {
		return "", err
	}
	if len(msgItemList) == 0 {
		return "", fmt.Errorf("miss question")
	}
	lastMsgItem := msgItemList[len(msgItemList)-1]

	fastGptMsgList := []FastGptMessage{}
	for _, msgItem := range msgItemList {
		role := "user"
		if msgItem.ChatRole == roadmap_rag_api.CHAT_ROLE_TYPE_CHAT_ROLE_ASSISTANT {
			role = "assistant"
		}
		fastGptMsgList = append(fastGptMsgList, FastGptMessage{
			Role:    role,
			Content: msgItem.Content,
		})
	}

	//准备请求
	reqUrl := fmt.Sprintf("%s/v1/chat/completions", ragConfigItem.BasicConfig.BaseApiAddr)
	reqData, err := json.Marshal(&FastGptRequest{
		AppId:    "6879a103808be63e01e4a081",
		Stream:   true,
		Messages: fastGptMsgList,
	})
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest("POST", reqUrl, bytes.NewBuffer(reqData))
	if err != nil {
		return "", err
	}
	req.Header.Set("Authorization", "Bearer "+ragConfigItem.BasicConfig.ApiKey)
	req.Header.Set("Content-Type", "application/json")

	//处理响应
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	resultContentList := []string{}
	scanner := bufio.NewScanner(resp.Body)
	for scanner.Scan() {
		line := scanner.Text()
		line = strings.Trim(line, " \r\n\t")
		if strings.HasSuffix(line, "[DONE]") {
			break
		}
		if strings.HasPrefix(line, "data:") {
			obj := &FastGptAnswerItem{}
			err = json.Unmarshal([]byte(line[5:]), obj)
			if err != nil {
				return "", err
			}
			if obj.Code != 0 && obj.Message != "" {
				return "", fmt.Errorf("%s", obj.Message)
			}
			if len(obj.Choices) == 0 {
				continue
			}

			resultContentList = append(resultContentList, obj.Choices[0].Delta.Content)
			s.Send(&roadmap_rag_api.SendMessageResponse{
				Code:                 roadmap_rag_api.SendMessageResponse_CODE_OK,
				UserMessageId:        lastMsgItem.MessageId,
				AssistantTimeStamp:   assistantTimeStamp,
				AssistantMessageId:   assistantMessageId,
				AssistantContentPart: obj.Choices[0].Delta.Content,
			})
		}
	}

	return strings.Join(resultContentList, ""), nil
}
